// pages/recommendSong/recommendSong.js
import request from '../../utils/request';
import PubSub from 'pubsub-js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    day:'', //天
    month:'', //月
    recommendSongList:[],  //推荐歌曲列表数据
    index:0  //点击的音乐下标
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //判断用户是否登录
    let userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon:'none',
        success:() =>{
          //跳转到登录页面
          wx.reLaunch({
            url: '/pages/login/login',
          })
        }
      })
    }
    this.setData({
      day: new Date().getDate(),
      month: new Date().getMonth() + 1
    })
    //获取每日推荐数据
    this.getrecommendSong();

    //订阅songDetail页面发布的消息
    PubSub.subscribe('switchType',(msg,type) =>{
      let {recommendSongList,index} =this.data
      if (type === 'Previous') {//上一首
        (index === 0) && (index = recommendSongList.length)
        index -=1;  
      } else {//下一首
        (index === recommendSongList.length -1) && (index = -1)
        index +=1;
      }
      this.setData({
        index
      })
      let musicId = recommendSongList[index].id;
      PubSub.publish('musicId',musicId);
    })
  },

  //请求每日歌曲数据
  async getrecommendSong(){
    let recommendSongList = await request('/recommend/songs');
    this.setData({
      recommendSongList: recommendSongList.recommend
    })
  },

  //跳转到songDetail的页面
  async toSongDetail(event){
    let {musicid,index} =event.currentTarget.dataset;
    this.setData({
      index
    })
    let musicAudioItem = await request('/song/url',{id:musicid});
    if (musicAudioItem.data[0].url == null) {
      wx.showToast({
        title: '歌曲已经不存在',
        icon: 'none'
      })
    }else{
      wx.navigateTo({
        url: '/pages/songDetail/songDetail',
        success:(res) =>{
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('musicContent',{musicId:musicid, musicUrl: musicAudioItem.data[0].url})
        }
      })
    } 
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})